//随机生成6-40位大小写字母、数字构成的密钥(不是大小写字母和数字都包含)
export function generateRandomString(minLength: number, maxLength: number) {
  const length =
    Math.floor(Math.random() * (maxLength - minLength + 1)) + minLength
  const charset =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let randomString = ''
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * charset.length)
    randomString += charset[randomIndex]
  }
  return randomString
}
//随机生成6-40位大小写字母、数字、标点符号（四者都包含）构成的密钥
export function generateRandomThreeTypesString(
  minLength: number,
  maxLength: number,
  includeSpecial: boolean = true //是否包含特殊字符
): string {
  const charset = !includeSpecial
    ? {
        upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        lower: 'abcdefghijklmnopqrstuvwxyz',
        digits: '0123456789'
      }
    : {
        upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        lower: 'abcdefghijklmnopqrstuvwxyz',
        digits: '0123456789',
        special: "_()`~!@#$%^&*-+=|{}[]:;'<>,.?"
      }
  const charsetLength = Object.keys(charset).length
  // 确保长度在合理范围内
  const length = Math.max(minLength, charsetLength) // 最小长度为4，以确保包含大写、小写和数字和标点符号
  const randomLength =
    Math.floor(Math.random() * (maxLength - length + 1)) + length

  let randomString = ''

  // 确保至少包含一个大写字母、一个小写字母和一个数字
  randomString += charset.upper.charAt(
    Math.floor(Math.random() * charset.upper.length)
  )
  randomString += charset.lower.charAt(
    Math.floor(Math.random() * charset.lower.length)
  )
  randomString += charset.digits.charAt(
    Math.floor(Math.random() * charset.digits.length)
  )
  if (includeSpecial) {
    randomString += charset.special.charAt(
      Math.floor(Math.random() * charset.special.length)
    )
  }
  // 填充剩余长度的随机字符
  const allCharset =
    charset.upper + charset.lower + charset.digits + charset.special
  for (let i = charsetLength; i < randomLength; i++) {
    const randomIndex = Math.floor(Math.random() * allCharset.length)
    randomString += allCharset.charAt(randomIndex)
  }

  // 打乱字符串顺序以增加随机性
  randomString = randomString
    .split('')
    .sort(() => Math.random() - 0.5)
    .join('')

  return randomString
}
